package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.model.entity.*;
import com.atguigu.lease.model.enums.ItemType;
import com.atguigu.lease.web.admin.mapper.*;
import com.atguigu.lease.web.admin.service.*;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentDetailVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentItemVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentQueryVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentSubmitVo;
import com.atguigu.lease.web.admin.vo.fee.FeeValueVo;
import com.atguigu.lease.web.admin.vo.graph.GraphVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @author liubo
 * @description 针对表【apartment_info(公寓信息表)】的数据库操作Service实现
 * @createDate 2023-07-24 15:48:00
 */
@Service
public class ApartmentInfoServiceImpl extends ServiceImpl<ApartmentInfoMapper, ApartmentInfo>
        implements ApartmentInfoService {


    @Autowired
    private ApartmentFacilityService apartmentFacilityService;

    @Autowired
    private ApartmentFeeValueService apartmentFeeValueService;

    @Autowired
    private ApartmentLabelService apartmentLabelService;

    @Autowired
    private GraphInfoService graphInfoService;

    @Autowired
    private FacilityInfoMapper facilityMapper;

    @Autowired
    private FeeValueMapper feeValueMapper;

    @Autowired
    private LabelInfoMapper labelMapper;

    @Autowired
    private GraphInfoMapper graphInfoMapper;

    @Autowired
    private ApartmentInfoMapper apartmentInfoMapper;

    @Autowired
    private RoomInfoMapper roomInfoMapper;

    /**
     * 保存或者修改公寓的信息
     * @param apartmentSubmitVo
     */
    @Override
    public void saveOrUpdateApartment(ApartmentSubmitVo apartmentSubmitVo) {
        // 判断是否进行修改操作，如果有id就是修改，如果没有就是插入
        // 判断apartmentSubmitVo 是否有id
        Long id = apartmentSubmitVo.getId();
        // 先将公寓基本信息（ApartmentInfo）保存或者更新
        super.saveOrUpdate(apartmentSubmitVo);
        if (id != null) { //不为空就是修改，修改的话先进性删除
            // 更加公寓id删除 配套信息，杂费、标签、图片
            //1 删除公寓配套信息
            LambdaQueryWrapper<ApartmentFacility> apartmentFacilityLambdaQueryWrapper = new LambdaQueryWrapper<>();
            apartmentFacilityLambdaQueryWrapper.eq(ApartmentFacility::getApartmentId, apartmentSubmitVo.getId());
            apartmentFacilityService.remove(apartmentFacilityLambdaQueryWrapper);
            //2 删除杂费列表
            LambdaQueryWrapper<ApartmentFeeValue> apartmentFeeValueLambdaQueryWrapper = new LambdaQueryWrapper<>();
            apartmentFeeValueLambdaQueryWrapper.eq(ApartmentFeeValue::getApartmentId, apartmentSubmitVo.getId());
            apartmentFeeValueService.remove(apartmentFeeValueLambdaQueryWrapper);
            //3 删除标签列表
            LambdaQueryWrapper<ApartmentLabel> labelLambdaQueryWrapper = new LambdaQueryWrapper<>();
            labelLambdaQueryWrapper.eq(ApartmentLabel::getApartmentId, apartmentSubmitVo.getId());
            apartmentLabelService.remove(labelLambdaQueryWrapper);
            //4 删除图片
            LambdaQueryWrapper<GraphInfo> graphInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
            graphInfoLambdaQueryWrapper.eq(GraphInfo::getItemId, apartmentSubmitVo.getId());
            graphInfoLambdaQueryWrapper.eq(GraphInfo::getItemType, ItemType.APARTMENT);
            graphInfoService.remove(graphInfoLambdaQueryWrapper);
        }


        // 1 添加公寓配套数据
        // 一个公寓id对应多个配套数据，应该添加多个记录
        List<Long> facilityInfoIds = apartmentSubmitVo.getFacilityInfoIds();
        // 判断是否有id
        if (!CollectionUtils.isEmpty(facilityInfoIds)) {
            // 创建集合用于批量保存
            ArrayList<ApartmentFacility> afList = new ArrayList<>();
            facilityInfoIds.forEach(facilityInfoId -> {
                //创建apartmentFacility对象，向设置需要添加值
                ApartmentFacility apartmentFacility = ApartmentFacility.builder()
                        .apartmentId(apartmentSubmitVo.getId())  // 添加公寓id
                        .facilityId(facilityInfoId)
                        .build();     // 添加配套id
                afList.add(apartmentFacility);
            });
            apartmentFacilityService.saveBatch(afList);
        }

        //2 添加公寓杂费数据
        List<Long> feeValueIds = apartmentSubmitVo.getFeeValueIds();
        // 判断id是否存在
        if (!CollectionUtils.isEmpty(feeValueIds)) {
            // 创建集合存储杂费数据用于批量保存
            List<ApartmentFeeValue> apartmentFeeValueList = new ArrayList<>();
            feeValueIds.forEach(feeValueId -> {
                ApartmentFeeValue build = ApartmentFeeValue.builder()
                        .apartmentId(apartmentSubmitVo.getId())
                        .feeValueId(feeValueId)
                        .build();
                apartmentFeeValueList.add(build);
            });
            apartmentFeeValueService.saveBatch(apartmentFeeValueList);
        }

        //3 添加标签数据
        // 获取标签id数据
        List<Long> labelIds = apartmentSubmitVo.getLabelIds();
        // 判断id是否存在
        if (!CollectionUtils.isEmpty(apartmentSubmitVo.getLabelIds())) {
            // 创建集合用于批量保存
            List<ApartmentLabel> apartmentLabelList = new ArrayList<>();
            labelIds.forEach(labelId -> {
                ApartmentLabel apartmentLabel = ApartmentLabel.builder()
                        .apartmentId(apartmentSubmitVo.getId())
                        .labelId(labelId)
                        .build();
                apartmentLabelList.add(apartmentLabel);
            });
            apartmentLabelService.saveBatch(apartmentLabelList);
        }

        //4 添加图片数据
        // 获取图片id
        List<GraphVo> graphVoList = apartmentSubmitVo.getGraphVoList();
        //判断数据是否存在
        if (!CollectionUtils.isEmpty(graphVoList)) {
            List<GraphInfo> graphInfoList = new ArrayList<>();
            graphVoList.forEach(graphInfoVo -> {
                GraphInfo graphInfo = new GraphInfo();
                // 公寓id
                graphInfo.setItemId(apartmentSubmitVo.getId());
                // 类型id
                graphInfo.setItemType(ItemType.APARTMENT);
                // 图片名称
                graphInfo.setName(graphInfoVo.getName());
                // 图片地址
                graphInfo.setUrl(graphInfoVo.getUrl());
                graphInfoList.add(graphInfo);
            });
            graphInfoService.saveBatch(graphInfoList);
        }

    }

    /**
     * 根据id查询公寓的详细信息
     * @param id
     * @return
     */
    @Override
    public ApartmentDetailVo getDetailById(Long id) {
        // 1 根据公寓id查询公寓基本信息
        ApartmentInfo apartmentInfo = super.getById(id);
        if (apartmentInfo == null) {
            return null;
        }
        // 2 根据公寓id查询公寓配套信息
        List<FacilityInfo> facilityInfoList = facilityMapper.findFacilityListByApartmentId(id);
        // 3 根据公寓id查询标签数据
        List<LabelInfo> labelInfoList = labelMapper.findlabelInfoListByApartmentId(id);
        // 4 根据公寓id查询杂费数据
        List<FeeValueVo> feeInfoList =  feeValueMapper.findfeeByApartmentId(id);
        // 5 根据公寓id查询图片数据
        List<GraphVo>  graphVoList = graphInfoMapper.findListByItemTypeAndId(ItemType.APARTMENT,id);
        // 将查询的数据封装到ApartmentDetailVo中
        ApartmentDetailVo adminApartmentDetailVo = new ApartmentDetailVo();
        BeanUtils.copyProperties(apartmentInfo, adminApartmentDetailVo);

        adminApartmentDetailVo.setFacilityInfoList(facilityInfoList);
        adminApartmentDetailVo.setLabelInfoList(labelInfoList);
        adminApartmentDetailVo.setFeeValueVoList(feeInfoList);
        adminApartmentDetailVo.setGraphVoList(graphVoList);

        return adminApartmentDetailVo;
    }

    /**
     * 分页查询公寓的信息
     * @param page
     * @param queryVo
     * @return
     */
    @Override
    public IPage<ApartmentItemVo> selectApartmentInfoPage(IPage<ApartmentItemVo> page, ApartmentQueryVo queryVo) {
        return apartmentInfoMapper.pageApartmentItemByQuery(page,queryVo);
    }

    /**
     * 根据公寓id删除公寓信息
     * @param id
     */
    @Override
    public void removeApartmentById(Long id) {

        //判断如果公寓下面有房间，不能直接删除公寓  room_info
        //根据公寓id查询room_info表，看公寓在这个表是否存在房间信息
        LambdaQueryWrapper<RoomInfo> roomInfoQuery = new LambdaQueryWrapper<>();
        roomInfoQuery.eq(RoomInfo::getApartmentId, id);
        long count = roomInfoMapper.selectCount(roomInfoQuery);
        if (count > 0) {
            throw new RuntimeException("存在房间信息，不能删除");
        }

        // 删除公寓的基本信息
        super.removeById(id);
        //删除GraphInfo
        LambdaQueryWrapper<GraphInfo> graphInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        graphInfoLambdaQueryWrapper.eq(GraphInfo::getItemType, ItemType.APARTMENT);
        graphInfoLambdaQueryWrapper.eq(GraphInfo::getItemId, id);
        graphInfoService.remove(graphInfoLambdaQueryWrapper);
        //删除ApartmentLabel
        LambdaQueryWrapper<ApartmentLabel> labelInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        labelInfoLambdaQueryWrapper.eq(ApartmentLabel::getApartmentId,id);
        apartmentLabelService.remove(labelInfoLambdaQueryWrapper);
        //删除ApartmentFacility
        LambdaQueryWrapper<ApartmentFacility> facilityLambdaQueryWrapper = new LambdaQueryWrapper<>();
        facilityLambdaQueryWrapper.eq(ApartmentFacility::getApartmentId,id);
        apartmentFacilityService.remove(facilityLambdaQueryWrapper);
        //删除ApartmentFeeValue
        LambdaQueryWrapper<ApartmentFeeValue> feeValueLambdaQueryWrapper = new LambdaQueryWrapper<>();
        feeValueLambdaQueryWrapper.eq(ApartmentFeeValue::getApartmentId,id);
        apartmentFeeValueService.remove(feeValueLambdaQueryWrapper);


    }
}




